<?php
//This page requires SSL for all methods
//TODO: enable PHP exceptions (High priority)

//TODO: wrap into class for OO?

require_once("database.include.php");


/************************ TODO: switch *********************************/
//This is where we go from a query string to a php call.
//get method name from query string,
//then based on that method, get the query strings expected for those parameters
//and call the appropriate method
//then if ajax, return a valid xml response for that call 
//if login, do redirect
//TODO: when/where do we set a cookie for login session

/************************ Session not required methods (Non-Ajax) *************************/


//if fail, redirects to register page with fail message in query string
//if success, redirect to  login page
//the public key will be publicly accessible on the user profile page
function register( $userName, $password, $publicKey ) {
	//TODO: try
	//TODO: begin transaction
	//	$stmt = $conn->prepare('INSERT INTO users(name, password, public_key) VALUES(?, ?, ?)');
	//	$stmt->execute( array( userName, password, public_key ) );
		//TODO: redirect to login (private key is required to encrypt token for login)
	//TODO: catch, rollback, redirect to register page with query string error message
}

//if fail, redirects to login page with fail message in query string
//if success, logs user in, stores session cookie at client, and redirects to home page
//TODO: do we have access to all certificates at once, or do we need to specify the group as a parameter?
//if we need to specify the group, should this be ajax?

//encrypted with user's private key
//function login( userName, password, token, encryptedToken ) {
function login( $userName, $password ) {

	$username=$_GET["username"];
	$password=$_GET["password"];
	$token=$_GET["token"];

	
	//TODO: try
			//TODO: validations which throw exceptions on failure
			// Login consists of two two factors - a token encryption check and a user/password check
		
			// First check, tokent encryption.  To do this, we'll need to lookup the user's private key.
			// DB Call to get user public key
			//$stmt = $conn->prepare("SELECT public_key FROM USERS WHERE user_name = ?)");
			//$stmt->execute(array(publicKey));
		
			// With their private key, we can decrypt stuff encrypted by the user with their private key.
			// We ask the user to encrypt a token we sent them.  They will provide the token, and an encrypted form of that token.
			// We then decrypt the encrypted token to verify a match (if the user has the appropriate private key, this decrypted
			// token will match).
		
			// Call function to decript encrypted token with retreived public key
			//decryptedToken = decrypt(encryptedToken, publicKey);
		
			// Check for match - indicating that the provided encrypted token was indeed encrypted with the user's private key
			//if token != decryptedToken then {
			//	echo "tokenMismatch";
			//} else {
				// Token matched, user has private key and signed token correctly.  Match ID/Password
		
				// We now procede to the username/password matching.  Passwords are SHA1 hashed, so they're not in the clear.
				// We don't know what the password was that they typed, we simply match hashes.
				// Check for username and password match
			
				//$stmt = $conn->prepare("SELECT count(*) FROM USERS WHERE user_name = ? and password = ?)");
				//$stmt->execute(array(userName, password));
		
    			//if ($count = $stmt->fetch()) {
    			//	if count = 0 then {
				//		echo "passwordMismatch";
					// If count is greater than 0, we had a match, set username and password as cookies.
				//	} else {
				
					if( $username=="admin" && $password=="d033e22ae348aeb5660fc2140aec35850c4da997" ) {
						echo "yes";
						setcookie('username', $userName, false, '/privr', 'city-score.com');
						setcookie('password', $password, false, '/privr', 'city-score.com');
						setcookie('token', $token, false, '/privr', 'city-score.com');
					} else {
						echo "passwordMismatch";
					}	
		//TODO: if count is 1, then redirect to main page  --- Done through JS on client
		//TODO: if count is 0, redirect to login page      --- Done through JS on client
	//TODO: catch, redirect to login page with query string error
}

/*********************** Session required methods (Ajax) *********************************/

//public key only used to authenticate against delete message/delete group/delete invitation
//group public key is not displayed anywhere on the site
function createGroup( $userName, $groupName, $groupPublicKey, $groupDescription ) {
	//TODO: try
	//TODO: begin transaction
		$stmt = $conn->prepare('INSERT INTO group(name, public_key, description) VALUES(?, ?, ?)');
		$stmt->execute( array( groupName, groupPublicKey, groupDescription ) );
		
		$stmt = $conn->prepare('INSERT INTO group_user(group_name, user_name) VALUES(?, ?)');
		$stmt->execute( array( groupName, userName ) );
		
		//TODO: ajax update main
	//TODO: catch, rollback, redirect to main with query string error message
}

//callback success
//encrypted with invited user's public key
function inviteUser( $invitingUserName, $invitedUserName, $groupName, $encryptedGroupPrivateKey ) {
	//TODO: try
	//TODO: begin transaction
		$stmt = $conn->prepare('INSERT INTO group_invitation(inviting_user_name, invited_user_name, group_name, encrypted_group_private_key ) VALUES(?, ?, ?, ?)');
		$stmt->execute( array( invitingUserName, invitedUserName, groupName, encryptedGroupPrivateKey ) );
		
		//TODO: ajax update main
	//TODO: catch, rollback, redirect to main with query string error message
}

//after accept, added to group users table and invitation is deleted
//encrypted with group private key
function acceptGroupInvitation( $userName, $groupName, $encryptedGroupName ) {
	//TODO:
}


//remove group invitation which has not been accepted
//encrypted with group private key
function deleteGroupInvitation( $userName, $groupName, $encryptedGroupName ) {
	//TODO:
}

//returns success, updates list
//encrypted with group private key
function sendGroupMessage( $groupName, $userName, $encryptedMessage, $retentionMode ) {
	//TODO: try
	//TODO: begin transaction
		$expiration_date = null;
		//TODO: calculate expiration date if applicable
		$stmt = $conn->prepare('INSERT INTO MESSAGES(group_name, user_name, message, retention_mode, expiration_date ) VALUES(?, ?, ?, ?, ?)');
		$stmt->execute( array( groupName, userName, encryptedMessage, retentionMode, expiration_date ) );
		
		//TODO: ajax update main
	//TODO: catch, rollback, redirect to main with query string error message
}

//returns success, updates list
//encrypted with group private key
function deleteGroupMessage( $messageId, $groupName, $encryptedGroupName ) {
	//TODO: try
	//TODO: begin transaction
		//TODO: ensure that decrypted group name = group name
	
		$stmt = $conn->prepare('DELETE FROM MESSAGES where message_id = ?');
		$stmt->execute( array( messageId ) );
		
		//TODO: ajax update main
	//TODO: catch, rollback, redirect to main with query string error message
}

//returns success, updates list
//encrypted with group private key
function deleteGroup( $groupName, $encryptedGroupName ) {
	//TODO: try
	//TODO: begin transaction
		//TODO: ensure that decrypted group name = group name
	
		$stmt = $conn->prepare('DELETE FROM GROUP where group_name = ?');
		$stmt->execute( array( group_name ) );
		
		//TODO: ajax update main
	//TODO: catch, rollback, redirect to main with query string error message
}

function refreshMessages() {
	//TODO:
}

function refreshGroups() {
	//TODO:
}

function refreshGroupMembers() {
	//TODO:
}

function refreshInvitations() {
	//TODO:
}

function decrypt( $message, $publicKey ) {
	//TODO: Function that will perform a public key decryption of a specified message.  Usually this will be done for validation 
	//that a user is in possesion of a valid private key.
}

?>